/**
 * Created by u-fan on 2016/6/27.
 */
(function () {
    var $body=$("body");
    $.get("header.html",function (data) {
       $body.prepend(data);
    });
    $.get("footer.html",function (data) {
        $body.append(data);
        event.global();
        eventBind(getPageName());
    });

    //本地链接异步加载局部刷新；
    function loadPage(href) {
        href = href || location.href;
        var page = getPageName(href);
        var $oldPage = $(".page").fadeOut(200);

        $.get(href,function (data) {
            document.title=$(data).filter("title").text();
            $oldPage.after($(data).filter(".page").hide().fadeIn(400)).remove();
            eventBind(page);
        });
    }
    function eventBind (page) {
        event[page] && event[page]();
        if (page==="" || page==="index"){
            event.home();
            event.case();
        }
    }
    var event = {
        "global":function () {
            var host = location.host;
            $body.on("click","a[href]",function (e) {
                var href = this.href;
                if(href.indexOf(host)>=0 || history.pushState){
                    //e.preventDefault();
                    history.pushState({},"",href);
                    loadPage(href);
                      window.scrollTo(0, 0);
                    return false;
                }
            })
            //立即资询
                .on('click',".btn-consult",function () {
                    window.open("http://wpa.qq.com/msgrd?v=3&uin=403450978&site=qq&menu=yes");
                })
                //立即询价
                .on('click',".btn-enquiry",function () {
                    $(".pop-consult").slideDown(200);
                });
            //询价浮窗关闭
            $(".pop-consult")
                .on('click',".close",function () {
                    $(".pop-consult").slideUp(200);
                })
                .on('submit','.form-enquiry',function () {
                    saveMsg('enquiry',this);
                    return false;
                });

            window.onpopstate = function(event) {
                //if (event && event.state) {
                    loadPage();
                //}
            };
        },
        "home": function () {
            $(".scheme-tabs li").mouseover(function () {
                if ($(this).hasClass("active"))return;
                $(this).add($(this).siblings(".active")).toggleClass("active");
                var $info = $('.scheme-info li');
                var $old = $info.filter(":visible");
                $info.eq($(this).index()).css("z-index", "9").fadeIn(400, function () {
                    $old.hide();
                    $(this).css("z-index", "");
                });
                //$('.scheme-info').children(":eq(" + $(this).index() + "),:visible").fadeToggle(400);
            });
            $(".banner-slider").slider();
            $(".product-slider").slider({
                stamp: 0,		//切换间隔，为0时不自动切换，单位秒
                pointBar: ".product-tab",
                leftArrow: ".product-prev",
                rightArrow: ".product-next"
            });
            $(".slider-adv").slider({
                stamp: 0,		//切换间隔，为0时不自动切换，单位秒
                showArrow: false,
                pointBar: ".adv-pointer"
            });
        },
        "case": function () {
            $(".slider-case").slider({
                stamp: 6,		//切换间隔，为0时不自动切换，单位秒
                showArrow: false,
                pointBar: ".case-pointer",
                onChange: function (idx) {
                    $('.case-intro').filter(":eq(" + idx + "),:visible").fadeToggle(400);
                }
            });
        },
        "support":function () {
            $("form.complaint").on('submit',function (e) {
                e.preventDefault();
                    saveMsg('msg',this);
                 return false;
            });
        },
        "admin":function () {
            var $page = $(".page-admin");
            $.get("api/login.php",function (data) {
                if (data.status){
                    $page.children().toggle();
                }
            });
            $page.on("submit",".login-form",function (e) {
                var _form = $(this);
                _form.find('button').attr('disabled',true);
                $.post("api/login.php",$(this).serialize(),function (data) {
                    if (data.status){
                        $page.children().toggle();
                    }else{
                        _form.find(".login-info").text(data.msg);
                    }
                    _form[0].reset();
                    _form.find('button').attr('disabled',false);
                });
                return false;
            })
            .on("click",".logout",function () {
                location.href='api/logout.php';
                return false;
            })
                .on("click","#viewEnquiry",function () {
                    viewMsg("enquiry",'.enquiry');
                })
                .on("click","#viewConsult",function () {
                    viewMsg("msg",'.consult');
                });

            var $manageBody = $page.find(".manage-body");
            $manageBody.on("click",".item-del",function () {
                var $item = $(this).closest('.msg-list');
                var type = $item.hasClass("enquiry")?'enquiry':'msg';
                var idx = $item.index();
                $.post("api/del_msg.php",{type:type,idx:idx},function (data) {
                    if(data.status){
                        $item.fadeOut(500,function () {
                            $(this).remove();
                        });
                    }else{
                        alert("操作失败，请稍后再试！")
                    }
                })

            });
            var $tmps = $manageBody.children().remove();
            function viewMsg(type,el) {
                var $list = $tmps.filter(el).clone();
                var tmp=$list[0].outerHTML;
                $manageBody.fadeOut(100);
                $.post("api/get_msg.php",{type:type},function (data) {
                    if(data.status){
                        var html='';
                        for (var i=0,item;item=data.data[i++];){
                            html+=formatStr(tmp,item);
                        }
                        if(data.data.length==0) html = '<h4 class="padding-lg text-center">暂无数据！</h4>'
                        $manageBody.hide().html(html).fadeIn(300);
                    }else{
                        alert("请重新登陆，再试！")
                    }
                })
            }

        }
    };
    function saveMsg(type,_form){
        var url = "api/save_msg.php";
        var data = {time : new Date().getTime()};
        var _arr = $(_form).serializeArray();
        for(var i=0,item;item = _arr[i++];){
            if(!item.value || item.value.length<2){
                $(_form).find('[name='+item.name+']').addClass('error').focus();
                alert("请填写有效信息！");
                return false;
            }
            data[item.name] = item.value;
        }
        $(_form).find('button').attr('disabled',true);
        var param = {
            type:type,
            data:JSON.stringify(data)
        };
        $.post(url,param,function (data) {
            _form.reset();
            $(_form).find('button').attr('disabled',false);
            $(".pop-consult").slideUp(200);
            alert(data.msg);
        });
    }
    function getPageName(href) {
        href= href || window.location.href;
        href = href.substr(href.lastIndexOf("/")+1);
        return href.substr(0,href.indexOf("."));
    }
    function formatStr(str,args){
        str = str.replace(/{(\w*)}/g, function (match, key) {
            var re = args[key] || "";
            if(key=="time") re = new Date(re).toLocaleString();
            return re;
        });
        return str;
    }
}());
/**
 * Created by u-fan on 2016/7/10.
 */
+function ($) {
    var defaultSetting = {
        mod:"default",   //默认轮播方式
        active:0,       //当前页
        speed:600,		//速度
        stamp:5,		//切换间隔，为0时不自动切换，单位秒
        showArrow:true, //是否显示左右切换按钮
        pointBar:".point-bar",
        leftArrow:".slider-prev",
        rightArrow:".slider-next",
        onChange:function (idx) {} //切换事件回调
    };
    var isTransform = (function () {
        return !($('<div>').css("transform") === undefined)
    }());

    //定义插件接口
    function Plugin(el, option) {
        option = option || {};
        this.el = $(el);
        this.setting = $.extend({}, defaultSetting, option);

        this.$pointBar = option.pointBar?$(option.pointBar): this.el.find(defaultSetting.pointBar);
        this.$leftArrow = option.leftArrow?$(option.leftArrow): this.el.find(defaultSetting.leftArrow);
        this.$rightArrow = option.rightArrow?$(option.rightArrow): this.el.find(defaultSetting.rightArrow);

        $.extend(this, mods[this.setting.mod]);

        this.init();
        this.eventBind();
        this.go(0);
    }

    //添加通用方法
    $.extend(Plugin.prototype, {
        go: function (idx) {
            var side,
                s = this.setting,
                num = this.num;
            if (isNaN(idx) || idx < 0) { //idx为空下一页，-1上一页
                side = isNaN(idx) ? 1 : -1;
                idx = (s.active + side + num) % num;
            } else {
                side = (idx >= s.active) ? 1 : -1;
            }
            this.move(idx, side);
            if (s.stamp) this.autoPlay();
            this.onChange(idx);
        },
        goPre: function () {
            this.go(-1);
        },
        onChange:function (idx) {
            this.$pointBar.children(":eq(" + idx + "),.active").toggleClass("active");
            this.setting.active = idx;
            this.setting.onChange(idx);
        },
        autoPlay: function () {
            var self = this;
            clearTimeout(this.play);
            this.play = setTimeout(function () {
                self.go()
            }, this.setting.stamp * 1000)
        },
        eventBind: function () {
            var self = this,
                s = this.setting;
            //生成焦点绑定事件；
            if (this.$pointBar.size()>0){
                var $points =this.$pointBar.children();
                //生成默认point
                if($points.length<=0){
                    var point="";
                    for(var i=0;i<this.num;i++){
                        point+='<span class="item" data-idx="'+i+'"></span>';
                    }
                    $points = $(point).appendTo(this.$pointBar);
                }
                $points.click(function(){
                    if (!$(this).hasClass("active")){
                        self.go($(this).data("idx"));
                    }
                    return false;
                });
            }
            if (s.showArrow){
                if(this.$leftArrow.length==0){
                    this.$leftArrow = $('<div class="'+ s.leftArrow.substr(1)+' bg-trans">&lt; </div>');
                    this.$rightArrow = $('<div class="'+ s.rightArrow.substr(1)+' bg-trans">&gt; </div>');
                    this.el.append(this.$leftArrow ).append(this.$rightArrow);
                }
                this.$leftArrow.click(function(){self.goPre()});
                this.$rightArrow.click(function(){self.go()});
            }
        }
    });

    var mods = {
        //全副轮播切换；
        'default': {
            init: function () {
                var el = this.el;
                this.$items = el.find(".slider-item");
                this.num = this.$items.size();
                this.viewWidth = el.width();
                if (el.height() == 0) { //没有定义可视高度时，填充高度
                    if (this.$items.height()) {
                        el.height(this.$items.height());
                    } else {
                        this.$items.find("img").eq(0).one("load", function () {
                            el.height(this.height);
                        });
                    }
                }
            },
            move: function (idx, side) {//side为1或-1；表示运动方向1为向左滚动至下一张，-1为向右滚动上一张
                var $items = this.$items,
                    s = this.setting,
                    around = (side == 1) ? "left" : "right",
                    dir = (side == 1) ? "next" : "pre";
                var idxItem = $items.eq(idx).addClass(dir);
                idxItem[0].offsetWidth;  //进行一次读操作force reflow
                var moves = idxItem.add($items.eq(s.active)).addClass(around);

                setTimeout(function () {
                    moves.toggleClass("active").removeClass([around, dir].join(' '));
                }, s.speed);
                //不支持CSS动画，调用Jquery动画；
                if (!isTransform) {
                    var viewWidth = this.viewWidth;
                    idxItem.css("left", viewWidth * side);
                    moves.animate({"left": "-=" + viewWidth * side + "px"}, s.speed);
                }
            }
        },
        //步长滚动
        'step': {}
    };
    //注册到jquery插件
    $.fn.slider= function (option) {
        return this.each(function () {
            var $this = $(this);
            if (!$this.data("slider")){
                $this.data("slider",new Plugin(this,option))
            }
        })
    }
    //返回全局的构造函数；
    //创建实例 new Slider(".slider")
    //global.Slider = Plugin;
    //return Plugin;
}(jQuery);